#include "DrawThread.h"

#include <iostream>
#include <SDL/SDL.h>

using std::cout;
using std::cerr;
using std::endl;


DrawThread::DrawThread():
	Thread("DrawThread")
{
	cout << "drawthread constr" << endl;
}

DrawThread::~DrawThread()
{
	cout << "drawthread destr" << endl;
}


void DrawThread::init()
{
	cout << "drawthread init" << endl;
	prevtime = 0;
	nowtime  = 0;

	framerate = 3; // 100;
	frametime = 1000 / framerate;
}


void DrawThread::run()
{
	// store starting time
	prevtime = SDL_GetTicks();

	// TODO: perform one frame
	static int i = 0;
	cout << "draw " << i << endl;
	i++;


	// push event to swap buffers
	SDL_Event event;
	event.type = SDL_USEREVENT;
	SDL_PushEvent(&event);
	// TODO: wait for condition variable
	//SDL_CondWaitTimeout(cond, mutex, 15);


	// time the frames
	nowtime  = SDL_GetTicks();
	int timespent = nowtime   - prevtime;
	int timeleft  = frametime - timespent;
	if(timeleft > 5)
	{
		if(timeleft > frametime)
		{
			cerr << "timeleft is too large!" << endl;
			timeleft = frametime;
		}
		SDL_Delay(timeleft);
	}
	cout << prevtime << ", " << nowtime << ", "  << frametime << ", " << timespent << ", " << timeleft << endl;

}


void DrawThread::shutDown()
{
	cout << "drawthread shutDown" << endl;
}

